import re
import datetime
from kubernetes import client, config
from kubernetes.client.rest import ApiException

# 加载k8s集群配置（从 Pod 内部读取配置），创建API客户端
config.load_incluster_config()
batch_v1 = client.BatchV1Api()

def create_extract(start, end, ipflt, portflt, entityflt, appflt):
  # 定义 Job 的元数据
  job_name = f"uniextract-{datetime.datetime.now().strftime('%Y%m%d-%H%M%S')}"
  metadata = client.V1ObjectMeta(name=job_name, namespace='uniserver')
  
  # 定义挂载点和卷
  volume_mounts = [
    client.V1VolumeMount(
      name='unidsas',
      mount_path='/data'
    ),
    client.V1VolumeMount(
      name='uniextract',
      mount_path='/uniextract'
    ),
    client.V1VolumeMount(
      name='uniextract-script',
      mount_path='/uniextract-script'
    )
  ]

  volumes = [
    client.V1Volume(
      name='unidsas',
      host_path=client.V1HostPathVolumeSource(path='/data/unidsas')
    ),
    client.V1Volume(
      name='uniextract',
      host_path=client.V1HostPathVolumeSource(path='/data/uniextract')
    ),
    client.V1Volume(
      name='uniextract-script',
      config_map=client.V1ConfigMapVolumeSource(name='uniextract-script')
    )
  ]

  # 将字节码转换为以 - 分隔的十六进制表示
  bytecode = appflt.encode()
  hexstr = '-'.join(f'{byte:02x}' for byte in bytecode)

  # 获取unidsas镜像名
  image = None
  core_v1 = client.CoreV1Api()
  pod_list = core_v1.list_namespaced_pod('uniserver', label_selector='app=unidsas')
  for pod in pod_list.items:
    image = pod.spec.containers[0].image
       
  # 定义 Job 的容器和命令
  container = client.V1Container(
    name="uniextract", image=image,
    command=["sh", "-x",
             "/uniextract-script/uniextract.sh",
             start, end, ipflt, portflt, entityflt, hexstr],
    volume_mounts=volume_mounts,
    env=[client.V1EnvVar(name="TZ", value="Asia/Shanghai")]
  )

  # 定义 Job 的 Pod 模板
  template = client.V1PodTemplateSpec(
    metadata=client.V1ObjectMeta(labels={"app": "uniextract"}),
    spec=client.V1PodSpec(
      restart_policy="Never",
      containers=[container],
      volumes=volumes
    )
  )

  # 定义 Job 的规格，创建 Job 对象
  job_spec = client.V1JobSpec(template=template, backoff_limit=1)
  job = client.V1Job(api_version="batch/v1", kind="Job", metadata=metadata, spec=job_spec)

  try:
    api_response = batch_v1.create_namespaced_job(namespace='uniserver', body=job)
    print(f"Job created. Status='{api_response.status}'")
  except ApiException as e:
    print(f"Exception when creating Job: {e}")

def list_extract():
  jobs = []
  try:
    batch_v1 = client.BatchV1Api()
    job_list = batch_v1.list_namespaced_job('uniserver')
    core_v1 = client.CoreV1Api()
    
    for job in job_list.items:
      job_info = {
        'name': job.metadata.name,
        'start_time': job.status.start_time.timestamp() if job.status.start_time else None,
        'active': job.status.active,
        'succeeded': job.status.succeeded,
        'failed': job.status.failed
      }

      pod_list = core_v1.list_namespaced_pod('uniserver', label_selector=f'job-name={job.metadata.name}')
      for pod in pod_list.items:
        try:
          pod_log = core_v1.read_namespaced_pod_log(name=pod.metadata.name, namespace='uniserver')

          # 提取command部分并去掉前面的+
          command_pattern = r"^\+ (.*)"
          command_match = re.search(command_pattern, pod_log, re.MULTILINE)
          command = command_match.group(1) if command_match else None

          # 提取extract_file部分并去掉[OUT_FILE]/uniextract/
          extract_file_pattern = r"^\[OUT_FILE\]/uniextract/(.*)"
          extract_file_match = re.search(extract_file_pattern, pod_log, re.MULTILINE)
          extract_file = extract_file_match.group(1) if extract_file_match else None

          job_info['command'] = command
          job_info['extract_file'] = extract_file

        except ApiException as e:
          print(f"Exception when reading pod log: {e}")
      jobs.append(job_info)
  except ApiException as e:
    print(f"Exception when listing Jobs: {e}")
  return jobs
